// // 创建可写流
// const writeStream = fs.createWriteStream("test.txt");

// // 写入数据
// writeStream.write("Hello, Node.js 流！\n");
// writeStream.write("流式写入数据...\n");

// // 结束写入
// writeStream.end(() => {
//   console.log("数据写入完成");
// });

// // 监听 error 事件
// writeStream.on("error", (err) => {
//   console.error("写入发生错误:", err);
// });
const { Duplex, Writable, Readable } = require("stream");

class MyDuplex extends Writable {
  constructor(options) {
    super(options);
  }
  _write(chunk, encoding, callback) {
    process.stdout.write(chunk + ">>>>>>>>");
    process.nextTick(callback);
  }
}

const myDuplex = new MyDuplex();
myDuplex.write("hello", "utf-8", () => {
  console.log(6666);
});

const fs = require("fs");
const ws = fs.createWriteStream("test.txt ", {
  highWaterMark: 1,
});

let num = 0;
let flag = true;
let arr = ["啦", "狗", "教", "育"];
function executeWrite() {
  flag = true;
  while (num !== arr.length && flag) {
    // 返回的flag代表流的消费速度，如果返回false代表流的消费速度跟不上写入速度，需要等待下次写入 需要使用drain事件通知是否可以下次写入
    flag = ws.write(arr[num]);
    num++;
  }
}
executeWrite();
ws.on("drain", () => {
  executeWrite();
  console.log("可以写入");
});
